package com.it.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.bean.Menu;
import com.it.dto.MenuDTO;
import com.it.mapper.MenuMapper;
import com.it.page.PageQuery;
import com.it.service.MenuService;
import com.it.utils.AppUtils;
import com.it.vo.MenuVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service("menuService")
@RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {

    private final MenuMapper menuMapper;

    @Override
    public PageInfo<MenuVo> page(PageQuery<MenuDTO> pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());
        List<MenuVo> menus = menuMapper.selectTree(pageQuery.getQueryBody());
        return new PageInfo<>(menus);
    }

    @Override
    public List<Menu> list(Menu menu) {
        return menuMapper.selectTreeOption(menu);
    }

    @Override
    public void save(Menu menu) {
        if (Objects.nonNull(menu.getMode()) && menu.getMode() == 1) {
            menu.setIcon("");
            menu.setSort(0);
        }
        if (menu.getId() == null) {
            AppUtils.forSaveAudit(menu);
            menuMapper.save(menu);
        } else {
            AppUtils.forUpdateAudit(menu);
            menuMapper.updateByPrimaryKeySelective(menu);
        }
    }

    @Override
    public void delete(Long id) {
        Menu menu = menuMapper.selectByPrimaryKey(id);
        menu.setDeleted(true);
        AppUtils.forUpdateAudit(menu);
        menuMapper.updateByPrimaryKeySelective(menu);
    }

    @Override
    public List<MenuVo> tree() {
        return menuMapper.tree();
    }

    @Override
    public List<Menu> nodes() {
        return menuMapper.nodes();
    }

    @Override
    public List<Menu> underlings(Long id) {
        return menuMapper.underlings(id);
    }

}
